package com.wwwarehouse.usercenter.fragment.business_relationship;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.carddesk.CardDeskMessageStableCardBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.adapter.SelectPermissionPagerAdapter;
import com.wwwarehouse.usercenter.bean.business_relationship.BRCustomerFileCheckBean;
import com.wwwarehouse.usercenter.bean.business_relationship.BRCustomerFileListBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.wwwarehouse.usercenter.eventbus_event.DrawerMultipleResetTrebleEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


/**
 * Created by xiaoke.ni on 2017/10/11.
 * 客户/供应商档案信息
 * 供应商档案信息 SUPPLIER_PROFILE
 * 客户档案信息 CUSTOMER_PROFILE
 */


@Route(path = UserCenterConstant.PATH_AUTHORITY_BR_CUSTOMER_FILE_CHECK)
public class BRCustomerFileCheckFragment extends BaseFragment implements View.OnClickListener, BRCustomerFileCheckListFragment.OnButtonClickedListener {

    private View mView;

    private StateLayout mStateLayout;
    private ElasticScrollView mElasticScrollView;
    private CustomViewPagerInternal mCustomViewPagerInternal;
    private CirclePageIndicator mCirclePagerIndicator;

    private SelectPermissionPagerAdapter mViewPagerAdapter;

    private List<Fragment> mFragmentList;
    private List<ArrayList<BRCustomerFileListBean.BusinessListBean>> mFragmentDataList;
    private List<BRCustomerFileListBean.BusinessListBean> mAuthorLinkedList;
    private BRCustomerFileCheckBean bean;
//    private List<BRCustomerFileListBean.ScreeningTagsBean> filterList;
//    private List<BRCustomerFileListBean.ScreeningSalesMansBean> filterList2;

    private ArrayList<String> mBusinessUnitId;
    private int mListSize;
    private boolean isShow;
    private int mSelectedBubblePosition = 3;

    private ArrayList<String> salesManIds;
    private ArrayList<String> tagIds;
    private String searchText;
    private String orderSort = SORT_DESC;
    private int page = 1;

    public static String SORT_DESC = "DESC";
    public static String SORT_ASC = "ASC";
    public static int SIZE = 9;
    private boolean isFrist = true;
    private String relationType;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_pr, null);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    private void initView() {
        mStateLayout = (StateLayout) mView.findViewById(R.id.slt);
        mElasticScrollView = (ElasticScrollView) mView.findViewById(R.id.esv);
        mCustomViewPagerInternal = (CustomViewPagerInternal) mView.findViewById(R.id.cvpi);
        mCirclePagerIndicator = (CirclePageIndicator) mView.findViewById(R.id.cpi);

    }

    private void initEvent() {
    }

    @Override
    public void onButtonClicked() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof BRCustomerFileCheckFragment) {
            Bundle bundle = getArguments();
            CardDeskMessageStableCardBean.TasksBean taskBean = bundle.getParcelable("data");
            //CUSTOMER客户 SUPPLIER供应商
            if (taskBean.getTaskType().equals("CUSTOMER_PROFILE")) {
                mActivity.setTitle(getResources().getString(R.string.br_customer_file_info));
            } else if (taskBean.getTaskType().equals("SUPPLIER_PROFILE")) {
                mActivity.setTitle(getResources().getString(R.string.br_supplier_file_info));
            }
        }
    }

    @Override
    public void requestDatas() {
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            CardDeskMessageStableCardBean.TasksBean taskBean = bundle.getParcelable("data");
            if (taskBean != null) {
                mBusinessUnitId = (ArrayList<String>) taskBean.getBusinessIds();
                //CUSTOMER客户 SUPPLIER供应商
                if (taskBean.getTaskType().equals("CUSTOMER_PROFILE")) {
                    relationType = "CUSTOMER";
                } else if (taskBean.getTaskType().equals("SUPPLIER_PROFILE")) {
                    relationType = "SUPPLIER";
                }
            }
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mFragmentList = new ArrayList<>();
        mFragmentDataList = new ArrayList<>();
        mAuthorLinkedList = new ArrayList<>();
        mStateLayout.showProgressView(true);
        cardDeskOption();
        getRelationBusinessUnitListByInfo();
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    /**
     * 客户档案列表-信息卡
     */
    private void getRelationBusinessUnitListByInfo() {
        mStateLayout.showProgressView(true);
        Map<String, Object> map = new HashMap<>();
        map.put("buIds", mBusinessUnitId);//业务单位所有id
        map.put("orderSort", orderSort);
        if (!TextUtils.isEmpty(orderSort))
            map.put("orderType", "related_time");
        map.put("page", page);
        map.put("relationType", relationType);
        if (salesManIds != null && salesManIds.size() > 0)
            map.put("salesManIds", salesManIds);
        if (!TextUtils.isEmpty(searchText))
            map.put("searchText", searchText);
        map.put("size", SIZE);
        if (tagIds != null && tagIds.size() > 0)
            map.put("tagIds", tagIds);
        NoHttpUtils.httpPost(UserCenterConstant.GET_RELATION_BUSINESS_UNIT_LIST_BY_INFO, map, onResponseListener, 0);
    }


    private NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        bean = JSON.parseObject(commonClass.getData().toString(), BRCustomerFileCheckBean.class);
                        if (bean.getBusinessList().size() == 0){
                            mStateLayout.showEmptyView(getString(R.string.user_br_no_data), true);
                            mStateLayout.setEmptyListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    getRelationBusinessUnitListByInfo();
                                }
                            });
                        } else {
                            mStateLayout.showContentView();
                        }
                        /******** 设置侧滑菜单 *******/
                        if (isFrist) {
                            isFrist = false;
                            DeskDrawerMultipleTrebleFragment deskDrawerMultipleFragment = DeskDrawerMultipleTrebleFragment.newInstance(getString(R.string.user_br_screen), bean.getScreen(), 1);
                            ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
                        }
                        ((BaseCardDeskActivity) mActivity).disableDrawerLayout();
                        mFragmentList.clear();
                        int pages = 0;
                        if (bean.getTotal() > 0) {
                            pages = bean.getTotal() / bean.getSize();
                            if (bean.getTotal() % bean.getSize() !=  0)
                                pages++;
                        }
                        for (int i = 0; i < pages; i++) {
                            BRCustomerFileCheckListFragment listFragment = BRCustomerFileCheckListFragment.newInstance(i + 1, mBusinessUnitId, orderSort, tagIds, salesManIds, searchText, bean, relationType);
                            listFragment.setOnButtonClickedListener(BRCustomerFileCheckFragment.this);
                            mFragmentList.add(listFragment);
                        }
                        mCustomViewPagerInternal.removeAllViews();
                        mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                        mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
                        mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
                    } else {
                        mStateLayout.showEmptyView(commonClass.getMsg(), true);
                        mStateLayout.setEmptyListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                getRelationBusinessUnitListByInfo();
                            }
                        });
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

    private void cardDeskOption() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                ((BaseCardDeskActivity) mActivity).downPull_4();
            }

            @Override
            public void onUpPull() {

            }
        });

    }

    @Override
    public void filterClick() {
        if (peekFragment() instanceof BRCustomerFileCheckFragment) {
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    @Override
    public void sortClick(View anchor) {
        if (peekFragment() instanceof BRCustomerFileCheckFragment) {
            PopUpUtils.showBubbleInviteSort(getContext(), anchor, mSelectedBubblePosition, new PopUpUtils.OnChoiceListener() {
                @Override
                public void onChoice(int position) {
                    mSelectedBubblePosition = position;

                    switch (position) {
                        case 2:
                            // 获取权限时间由远到近
                            orderSort = SORT_ASC;
                            getRelationBusinessUnitListByInfo();
                            break;
                        case 3:
                            // 获取权限时间由近到远
                            orderSort = SORT_DESC;
                            getRelationBusinessUnitListByInfo();
                            break;
                        default:
                            break;
                    }
                }
            }, null, getString(R.string.user_br_time_asc), getString(R.string.user_br_time_desc));
        }
    }

    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof BRCustomerFileCheckFragment) {
            searchText = text;
            getRelationBusinessUnitListByInfo();
        }
    }

    @Override
    public void cancelClick() {
        if (peekFragment() instanceof BRCustomerFileCheckFragment) {
            searchText = null;
            getRelationBusinessUnitListByInfo();
        }
    }

    public void onEventMainThread(DrawerMultipleResetTrebleEvent event) {
        if (peekFragment() instanceof BRCustomerFileCheckFragment) {
            mBusinessUnitId = event.getSelectedPositionSet();
            tagIds = event.getSelectedPositionSet2();
            salesManIds = event.getSelectedPositionSet3();
            if (mBusinessUnitId.size() == 0)
                mBusinessUnitId = (ArrayList<String>) ((CardDeskMessageStableCardBean.TasksBean) getArguments().getParcelable("data")).getBusinessIds();
            getRelationBusinessUnitListByInfo();
        }


    }

}
